<template>
  <view>
    <view
        class="flex justify-center align-center relative bg-fff sticky z-3 h-120"
        id="container"
        :style="{top:`${top}px`}"
    >
      <!--骨架屏-->
      <view v-if="loading" class="flex align-center justify-center pb-30 pt-50">
        <view class="h-60 w-200 br-5 bg-f4f7f4"> </view>
        <view class="w-30 h-5 br-5 m-lr-10"></view>
        <view class="h-60 w-200 br-5 bg-f4f7f4"></view>
      </view>
      <date-picker
          class="datePicker z-999" :defaultStartDate="startTime" :defaultEndDate="endTime"
          @changeTime="changeTime">
      </date-picker>
      <u-dropdown ref="uDropdown" height="144" inactive-color="#2D8CF0" :close-on-click-mask="false"
        menu-icon="arrow-down-fill">
        <u-dropdown-item :title="dropDownTitle">
          <view class="bg-fff pb-30">
            <u-checkbox-group class="w-full" size="40">
              <view class="w-full flex flex-column p-lr-20">
                <view v-for="(item, index) in checkedStatusList" :key="index"
                  class="h-90 border-333333 br-10 pl-25 w-full flex align-center mb-20">
                  <u-checkbox class="w-full flex" :name="item.value" :disabled="false" v-model="item.checked"
                    shape="circle" active-color="#19BE6B">
                    <text class="color-333333 fz-32 ml-30"> {{ item.label }} </text>
                  </u-checkbox>
                </view>
              </view>
            </u-checkbox-group>
            <view v-if="statusCheckedList.length>0" class="m-lr-20 h-100 br-10 bg-2D8CF0 text-center fz-32 lh-100 color-fff"
              @tap="confirmStatus">
              <text>确定</text>
            </view>
            <view v-else class="m-lr-20 h-100 br-10 bg-BEBEBE text-center fz-32 lh-100 color-fff">
              <text>确定</text>
            </view>
          </view>
        </u-dropdown-item>
      </u-dropdown>
    </view>
    <list-skeleton v-if="loading"></list-skeleton>
    <view :style="{ minHeight: `calc(100vh - ${top}px - ${safeAreaInsets}px - 338rpx)` }">
      <view v-if="workList.length && !loading">
        <view
            class="flex"
            v-for="item in workList"
            :key="item.workOrderId"
            @longpress="handleLongpress"
        >
          <view class="w-50 flex align-center ml-20" v-if="isLongPress" @tap.stop="">
            <u-checkbox size="50" v-model="item.checked"></u-checkbox>
          </view>
          <view class="m-lr-20 mb-30 pl-20 p-tb-12 flex1 flex align-center justify-between bg-E9F8FF br-10 oh"  @tap="clickItem(item)">
            <view class="flex flex-column oh">
              <text class="fz-40 font-bold lh-56 mt-12 text-ellipsis">{{ item.workOrderName || '-'}}</text>
              <text class="fz-32 lh-45 mt-20 text-ellipsis">所属科室：{{item.departmentName || '-'}}</text>
              <text class="fz-32 lh-45 mt-10 text-ellipsis">巡检人：{{item.inspectionUser || '-'}}</text>
              <view class="flex mt-10">
                <text class="fz-32 lh-40">起止时间：</text>
                <view class="flex flex-column fz-32 lh-40">
                  <text>{{ timeFormat(item.startDate, item.workOrderStartTime)}}</text>
                  <text>{{ timeFormat(item.endDate, item.workOrderEndTime)}}</text>
                </view>
              </view>
            </view>
            <view class="relative mr-30">
              <CustomCircleProgress
                :border-width="8"
                :size="128"
                :percent="getOrderPercentage(item)"
                :active-color="getOrderStatusColor(item.status)"
              >
                <view class="h-full w-full lh-center" :style="{ 'color': getOrderStatusColor(item.status) }">
                  <text class="fz-30">
                    {{ item.status===inspectionStatusList[2].value || item.status===inspectionStatusList[6].value ? '超时' : getStatusName(item.status)}}
                  </text>
                </view>
              </CustomCircleProgress>
            </view>
          </view>
        </view>
      </view>
      <empty-icon v-else ></empty-icon>
    </view>

    <view class="flex align-center justify-between h-120 sticky bottom-100 bg-fff z-10 p-lr-50" v-if="isLongPress"
      :style="{ bottom: `calc(100rpx + ${safeAreaInsets}px)` }">
      <view class="h-60 w-120 br-5 border-2D8CF0 fz-28 color-2D8CF0 lh-60 text-center" @tap="cancleLongPress">
        <text>取消</text>
      </view>
      <view class="flex">
        <view
          class="h-60 w-200 br-5 border-2D8CF0 fz-28 color-2D8CF0 lh-60 text-center mr-20"
          :class="isAllowDelay ? 'allowDelay' : 'disAllowDelay'"
          @tap="isAllowDelay ? isTimePickerShow = true : isTimePickerShow = false"
        >
          <text>延长工单</text>
        </view>
        <view class="h-60 w-120 br-5 border-2D8CF0 fz-28 color-fff lh-60 text-center"
          :class="isAllowDispatch ? 'allowDispatch' : 'disAllowDispatch'" @tap="dispatch">
          <text>派单</text>
        </view>
      </view>
    </view>

    <u-picker
      :defaultTime="defaultTime"
      v-model="isTimePickerShow"
      :params="params"
      mode="time"
      safe-area-inset-bottom
      :title="dropDownTitle"
      @confirm="confirmDelay"
      control
    >
    </u-picker>
  </view>
</template>

<script>
import CustomCircleProgress from '../../components/CustomCircleProgress'
import EmptyIcon from "@/components/EmptyIcon/EmptyIcon";
import getNavBarHeight from "@/mixins/getNavBarHeight";
import {allStatusList , delayEndDateBatch} from "@/api/inspection/task";
import DatePicker from "@/components/DatePicker/DatePicker";
import dayjs from '@/libs/dayjs.min.js'
import ListSkeleton from "../../components/ListSkeleton";

import { INSPECTION_ORDER_STATUS } from '@/utils/dict'

const inspectionStatusList = Object.keys(INSPECTION_ORDER_STATUS).map(key => INSPECTION_ORDER_STATUS[key])

export default {
  name: "workAll",
  components: {ListSkeleton, EmptyIcon, DatePicker, CustomCircleProgress},
  mixins:[getNavBarHeight],
  data() {
    return {
      hasNext: false,
      pageNum: 1,
      pageSize: 10,
      workList:[],
      startTime: '',
      endTime: '',
      taskList: '',
      selfTaskList: '',
      loading: true,
      isLongPress: false,
      checkedStatusList: [],
      safeAreaInsets: 0, //底部安全区高度
      defaultTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      isTimePickerShow: false,
      params: {
        year: true,
        month: true,
        day: true,
        hour: false,
        minute: false,
        second: false
      },
    }
  },
  created(){
    if(this.$store.getters.isFromHome2Work){
      const orderType = this.$store.getters.orderType
      if(orderType==='unDone'){
        const WILL = inspectionStatusList[1]
        const DOING = inspectionStatusList[3]
        this.checkedStatusList = inspectionStatusList.map(e=>{
          const el = { ...e, checked: false }
          const status = el.value
          if(status === WILL.value || status === DOING.value){
            el.checked = true
          }
          return el
        })
      }
      else if(orderType==='done'){
        const FINISHED = inspectionStatusList[4]
        const SIGNED = inspectionStatusList[5]
        this.checkedStatusList = inspectionStatusList.map(e=>{
          const el = { ...e, checked: false }
          if(el.value === FINISHED.value || el.value === SIGNED.value){
            el.checked = true
          }
          return el
        })
      }
      this.$store.commit('SET_ISFROMHOME2WORK', false)
    }else{
      this.checkedStatusList = inspectionStatusList.map(e=>{return { ...e, checked: true }})
    }
    uni.getSystemInfo({
      success: (res) => {
        // #ifdef MP-WEIXIN
        this.safeAreaInsets = res.screenHeight - res.safeArea.bottom
        // #endif
        // #ifndef MP-WEIXIN
        this.safeAreaInsets = res.safeAreaInsets.bottom
        // #endif
      }
    })
    this.taskList = this.$auth.hasPermiOr(['inspection:task:list', 'inspection:workOrder:list'])
    this.selfTaskList = this.$auth.hasPermiOr(['inspection:task:assignSelf', 'inspection:workOrder:assignSelf'])
    const today = dayjs().format('YYYY-MM-DD')
    this.startTime = today
    this.endTime = today
    this.doQuery().then(res => {
      this.hasNext = res.hasNext
      this.workList = res.rows
    }).finally(() => {
      this.loading = false
    })
  },
  computed:{
    STATUS(){ return INSPECTION_ORDER_STATUS },
    inspectionStatusList() {return inspectionStatusList},
    statusCheckedList(){
      return this.checkedStatusList.filter(item=>item.checked)
    },
    dropDownTitle(){
      if(this.statusCheckedList.length===0){
        return '未选择'
      }
      if(this.statusCheckedList.length===this.checkedStatusList.length){
        return '全部类型'
      }else{
        return this.statusCheckedList.map(item=>item.label).join(",")
      }
    },
    statusCheckedValue(){
      return this.statusCheckedList.map(item=>item.value).join(",")
    },
    selectionList(){
      return this.workList.filter(item=>item.checked)
    },
    isAllowDispatch () {
      if(this.selectionList.length===0) return false
      return this.selectionList.every(item => {
        const status = item.status
        return status === this.STATUS.UNDISTRIBUTED.value || status === this.STATUS.WILL.value || status === this.STATUS.DOING.value
        }
      )
    },
    isAllowDelay(){
      if(this.selectionList.length===0) return false
      return this.selectionList.every(item => {
        const status = item.status
        return status === this.STATUS.OVERTIME.value || status === this.STATUS.TIMEOUT.value
        }
      )
    }
  },
  methods:{
    clickItem(item) {
      if(this.isLongPress){
        item.checked = !item.checked
        return
      }
      if(item.status === this.STATUS.FINISHED.value){
        this.$tab.navigateTo('/pages/work/work-order-detail?workOrderId='+item.workOrderId)
      }else{
        this.$tab.navigateTo('/pages/work/all-order-detail?workOrderId='+item.workOrderId)
      }
    },
    reachBottom(){
      if(this.hasNext){
        this.pageNum ++
        this.doQuery().then(res => {
          this.hasNext = res.hasNext
          this.workList= [...this.workList,...res.rows]
        })
      }
    },

    changeTime(e){
      this.pageNum = 1
      this.startTime = e.startTime ? dayjs(e.startTime).format('YYYY-MM-DD') : '';
      this.endTime = e.endTime ? dayjs(e.endTime).format('YYYY-MM-DD') : '';
      this.doQuery().then(res => {
        this.hasNext = res.hasNext
        this.workList= res.rows
      })
    },

    doQuery(){
      const params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        statusList: this.statusCheckedValue,
      }
      params.startDate = this.startTime
      params.endDate = this.endTime
      return allStatusList(params).then(res => {
        res.rows = res.rows.map(item => {
          return { ...item, checked: false }
        })
        return Promise.resolve(res)
      }).catch(() => {
        this.loading = false
      })
    },
    //批量延长截止时间
    confirmDelay(e){
      const now = new Date()
      let delayEndDate = `${e.year}-${e.month}-`
      if(now.getFullYear() === parseInt(e.year) && now.getMonth()+1 === parseInt(e.month) && now.getDate() > parseInt(e.day)){
        delayEndDate += now.getDate()
      }else{
        delayEndDate += e.day
      }
      const workOrderIdList = this.selectionList.map(item => item.workOrderId)
      delayEndDateBatch({workOrderIdList, delayEndDate}).then(res => {
        if(res.code == 200){
          this.pageNum = 1
          this.isLongpress = false
          this.doQuery().then(res => {
            this.hasNext = res.hasNext
            this.workList= res.rows.map(item => {
              return {...item, checked: false}
            })
          })
        }
      })
    },
    //派单操作(批量分配工程师)
    dispatch () {
      if(this.isAllowDispatch){
        const workOrderIdList = this.selectionList.map(item => item.workOrderId)
        const hospitalId = this.selectionList[0].hospitalId
        const companyId = this.selectionList[0].companyId
        this.$tab.navigateTo(`/pages/work/choose-worker?workOrderIdList=${workOrderIdList}&hospitalId=${hospitalId}&companyId=${companyId}&byBatch=1`)
      }
    },
      //百分比-UI
    getOrderPercentage (item) {
      if(item.finishedStandard && item.totalStandard){
        return Math.floor((item.finishedStandard / item.totalStandard)*100) > 100 ? 100 : Math.floor((item.finishedStandard / item.totalStandard)*100)
      }
      const status = item.status
      if (!status) return 0
      switch (status) {
        case this.inspectionStatusList[0].value: return 0
        case this.inspectionStatusList[1].value: return 0
        case this.inspectionStatusList[3].value: return 50
        case this.inspectionStatusList[4].value: return 100
        case this.inspectionStatusList[5].value: return 100
        default: return 0
      }
    },
    //状态显示颜色
    getOrderStatusColor (status) {
      switch (status) {
        case this.inspectionStatusList[0].value: return ''
        case this.inspectionStatusList[1].value: return ''
        case this.inspectionStatusList[2].value: return '#FF6262'
        case this.inspectionStatusList[3].value: return '#2d8df2'
        case this.inspectionStatusList[4].value: return '#19BE6B'
        case this.inspectionStatusList[5].value: return '#19BE6B'
        case this.inspectionStatusList[6].value: return '#FF6262'
        default: return ''
      }
    },
    //状态-标签
    getStatusName (status) {
      const result = this.inspectionStatusList.find(item => item.value === status)
      return result ? result.label : ''
    },
    //取消长按多选
    cancleLongPress () {
      this.workList.forEach(item => {
        item.checked = false
      })
      this.isLongPress = false
    },
    //长按多选
    handleLongpress () {
      //长按手机震动并且显示复选框
      uni.vibrateShort({
        success: function () { }
      });
      this.isLongPress = true
    },
    //确定选择工单状态
    confirmStatus () {
      this.pageNum = 1
      this.doQuery().then(res => {
        this.hasNext = res.hasNext
        this.workList = res.rows.map(item => {
          return { ...item, checked: false }
        })
      })
      this.$refs.uDropdown.close();
    },
    timeFormat(date, time){
      if(!date || !time){
        return '-'
      }
      return date + ' ' + time.split(':')[0] + ":" + time.split(':')[1]
    },
    show(){
      this.pageNum = 1
      this.doQuery().then(res => {
        this.hasNext = res.hasNext
        this.workList = res.rows
      }).finally(() => {
        this.loading = false
      })
    },
    hide(){
      this.loading = true
    },
    showContent(item){
      if(!item.totalStandard){
        return '-'
      }
      return Math.floor((item.finishedStandard / item.totalStandard)*100) > 100 ? '100%' : Math.floor((item.finishedStandard / item.totalStandard)*100) + '%'
    }
  },
}
</script>

<style scoped>
.datePicker {
  position: absolute;
  left: 40rpx
}
.allowDispatch{
  border: 2rpx solid #2d8cf0;
  background: #2d8cf0;
}
.disAllowDispatch{
  border: 2rpx solid #2d8cf050;
  background: #2d8cf050;
}
.disAllowDelay{
  border: 2rpx solid #CCCCCC;
  color: #88888850;
  background: #F1F1F150;
}
.allowDelay{
  border: 2rpx solid #2d8cf0;
  color: #2d8cf0;
}
</style>
